Switch (Case) Statment in Bash
The case statement is useful and processes faster than an else-if ladder. Instead of checking all if-else conditions, the case statement directly select the block to execute based on an input.
Create the first program using the case statement in a shell script. The program takes input from the user and executes statements based on the input value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/bin/bash read -p "Enter your choice [yes/no]:" choice case $choice in yes) echo "Thank you" echo "Your type: Yes" ;; no) echo "Ooops" echo "You type: No" ;; *) echo "Sorry, invalid input" ;; esac |
Save the above script in case1.sh and execute the script on bash shell.
chmod +x case1.sh ./case1.sh Enter your choice [yes/no]:yes Thank you Your type: Yes ./case1.sh Enter your choice [yes/no]:no Ooops You type: No ./case1.sh Enter your choice [yes/no]:anything Sorry, invalid input
Script Execution Process:
- Set the execute permission on shell script.
- Executed the script first time and input “yes” to choice variable. Case matches the string with available options yes). Then executed code block under yes option.
- Executed the script second time and input “no” to choice variable. Case matches the string with available options no). Then executed code block under no option.
- Executed the script third time and input “anything” to choice variable. Case found not matches under available options for this string. In this situation case uses wildcard *) and executed statments under it.
Multple Strings in Case Options
You can define more than one string in the matching pattern under case statement in shell scripting. Check sample script here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/bin/bash read -p "Enter your choice [yes/no]:" choice case $choice in Y/y/Yes/YES/yes) echo "Thank you" echo "Your type: Yes" ;; N/n/No/NO/no) echo "Ooops" echo "You type: No" ;; *) echo "Sorry, invalid input" ;; esac |
Patterns Matching in Case Statement
You can use wildcard characters like *,? and [] with the case statement. But still, some of the braces expansion still not work. Now, you can set shopt -s extglob to use extended pattern matching.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #!/bin/bash read -p "Enter a string:" choice shopt -s extglob case $choice in a*) ### matches anything starting with "a" #script here ;; b?) ### matches any two-character string starting with "b" #script here ;; s[td]) ### matches "st" or "sd" #script here ;; r[ao]m) ### matches "ram" or "rom" #script here ;; me?(e)t) ### matches "met" or "meet" #script here ;; @(a|e|i|o|u)) ### matches one vowel #script here ;; *) ### Catchall matches anything not matched above #script here ;; esac |
Save above script in a shell script and execute it with various inputs and study about its execution.